//
//  UITextField+Limit.m
//  Live
//
//  Created by goldeneye on 2017/8/22.
//  Copyright © 2017年 goldeneye by smart-small. All rights reserved.
//

#import "UITextField+Limit.h"
#import <objc/runtime.h>



static NSString *kLimitMaxLengthKey = @"kLimitMaxLengthKey";
static NSString *kLimitVTypeKey = @"kLimitVTypeKey";


static const void *vLimitTypeKey = &vLimitTypeKey;

@interface UITextField()<UITextFieldDelegate>



@end

@implementation UITextField (Limit)

- (void)setVLimitType:(LimitValidationType)vLimitType
{
    objc_setAssociatedObject(self, vLimitTypeKey, [NSNumber numberWithInteger:vLimitType], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (LimitValidationType)vLimitType
{
    NSNumber * number =   objc_getAssociatedObject(self, vLimitTypeKey);
    
    return  [number intValue];
    
}

- (void)setLimitTextLength:(int)length{
    
    self.delegate = nil;
    self.keyboardType = UIKeyboardTypeDefault;
   
    NSNumber * vTypeNumber = objc_getAssociatedObject(self, (__bridge  const void *)(kLimitVTypeKey));
    int vType = [vTypeNumber intValue];
    
    NSLog(@"vType===%i",vType);
  
    
    objc_setAssociatedObject(self, (__bridge  const void *)(kLimitMaxLengthKey), [NSNumber numberWithInt:length], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    
    if (vType != LIMITVALIDATION_TYPE_DECIMAL_VALIDATED) {
        
        [self addTarget:self action:@selector(textFieldLengthLimit:) forControlEvents:UIControlEventEditingChanged];
    }
    

    
}
- (void)textFieldLengthLimit:(UITextField *)textField{
    
    NSNumber * vTypeNumber = objc_getAssociatedObject(self, (__bridge  const void *)(kLimitVTypeKey));
    int vType = [vTypeNumber intValue];
    if (vType != LIMITVALIDATION_TYPE_DECIMAL_VALIDATED) {
        NSNumber *maxLengthNumber = objc_getAssociatedObject(self, (__bridge  const void *)(kLimitMaxLengthKey));
        int maxLength = [maxLengthNumber intValue];
        
        
        NSString *toBeString = textField.text;
        NSLog(@"toBeString====%@ , maxLength = %i ",toBeString,maxLength);
        
        NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
        if([lang isEqualToString:@"zh-Hans"]) { //简体中文输入，包括简体拼音，健体五笔，简体手写
            UITextRange *selectedRange = [textField markedTextRange];
            //获取高亮部分
            UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
            //没有高亮选择的字，则对已输入的文字进行字数统计和限制
            if(!position) {
                if(toBeString.length > maxLength) {
                    textField.text = [toBeString substringToIndex:maxLength];
                }
            }
            //有高亮选择的字符串，则暂不对文字进行统计和限制
            else{
                
            }
        }
        //中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        else{
            if(toBeString.length > maxLength) {
                textField.text = [toBeString substringToIndex:maxLength];
            }
        }

    }
    
 
}

//设置类型
- (void)setLimitValidationType:(LimitValidationType)validationType{
    
    // self.vType = validationType;
    
    objc_setAssociatedObject(self, (__bridge  const void *)(kLimitVTypeKey), [NSNumber numberWithInt:validationType], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    NSNumber * vTypeNumber = objc_getAssociatedObject(self, (__bridge  const void *)(kLimitVTypeKey));
    int vType = [vTypeNumber intValue];
    
    NSLog(@"vTyp=======%i",vType);
    
    //数字
    if (vType == LIMITVALIDATION_TYPE_NUM_VALIDATED) {
        //字母+数字
        self.delegate = self;
        self.keyboardType = UIKeyboardTypeNumberPad;
    }else if (vType ==  LIMITVALIDATION_TYPE_LETTERNUM_VALIDATED)
    {
        //字母+数字
        self.delegate = self;
        self.keyboardType = UIKeyboardTypeASCIICapable;
    }else if (vType == LIMITVALIDATION_TYPE_DECIMAL_VALIDATED)
    {
    
        //小数类型
        self.delegate = self;
        self.keyboardType = UIKeyboardTypeDecimalPad;
    }
    else{
        self.delegate = nil;
        self.keyboardType = UIKeyboardTypeDefault;
        
    }
    NSLog(@"vType===%i",vType);
    
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
   
    
    
    
    if ([string isEqualToString:@""]) {
        
        return YES;
    }else{
        
        NSNumber * vTypeNumber = objc_getAssociatedObject(self, (__bridge  const void *)(kLimitVTypeKey));
        int vType = [vTypeNumber intValue];
        
        NSNumber *maxLengthNumber = objc_getAssociatedObject(self, (__bridge  const void *)(kLimitMaxLengthKey));
        int maxLength = [maxLengthNumber intValue];
        
        
        NSLog(@"maxLength===%i",maxLength);
        
        if (vType ==  LIMITVALIDATION_TYPE_NUM_VALIDATED) {
            
            NSCharacterSet *cs;
            cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
            
            
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
            
            BOOL canChange = [string isEqualToString:filtered];
            
            
            return textField.text.length>= maxLength? NO: canChange;
            
            
        }else if(vType ==  LIMITVALIDATION_TYPE_LETTERNUM_VALIDATED){
            
            
            NSCharacterSet *cs;
            cs = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] invertedSet];
            
            
            NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
            
            BOOL canChange = [string isEqualToString:filtered];
            
            
            return textField.text.length>= maxLength? NO: canChange;
            
            
        }else if (vType == LIMITVALIDATION_TYPE_DECIMAL_VALIDATED)
        {
        
            
            
            
            // 当前输入的字符是'.'
            if ([string isEqualToString:@"."]) {
                
                // 已输入的字符串中已经包含了'.'或者""
                if ([textField.text rangeOfString:@"."].location != NSNotFound || [textField.text isEqualToString:@""]) {
                    
                    return NO;
                } else {
                    
                    return YES;
                }
            } else {// 当前输入的不是'.'
                
                // 第一个字符是0时, 第二个不能再输入0
                if (textField.text.length == 1) {
                    
                    unichar str = [textField.text characterAtIndex:0];
                    if (str == '0' && [string isEqualToString:@"0"]) {
                        
                        return NO;
                    }
                    
                    if (str != '0' && str != '1') {// 1xx或0xx
                        
                        return YES;
                    } else {
                        
                        if (str == '1') {
                            
                            return YES;
                        } else {
                            
                            if ([string isEqualToString:@""]) {
                                
                                return YES;
                            } else {
                                
                                return NO;
                            }
                        }
                        
                        
                    }
                }
                
                // 已输入的字符串中包含'.'
                if ([textField.text rangeOfString:@"."].location != NSNotFound) {
                    
                    NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
                    [str insertString:string atIndex:range.location];
                    
                    NSLog(@"str=====%@",str);
                    
                    if (str.length >= [str rangeOfString:@"."].location + 4) {
                        
                        return NO;
                    }
                    NSLog(@"str.length = %ld, str = %@, string.location = %ld", str.length, string, range.location);
                    
                    
                } else {
                    
                    if (textField.text.length > maxLength-1) {
                        
                        return range.location < maxLength;
                    }
                }
                
                
            }
        
            return YES;
        
        
        }
        
        else{
            
            return YES;
        }
        
        
        
    }
    
    
}

@end
